package hojadetrabajo_6;

public class HuffmanTransversor
{
    private Node rootNode;
    private char c;
    private char charArray[];
    private int i=0,j=0;
    public String finalBitPattern = "";
    private static char tabla[] = new char[100];
    private static int con=0,cuantos=0;
    private static boolean ban=false;
    private String codigos[] = new String[100];
    private char chars[] = new char[100];
    private int frec[] = new int[100];
    
    public HuffmanTransversor(Node myNode, char [] charArray)
    {
        char t1,t2;
        String temp;
        int i;
        ban=false;
        rootNode = myNode;
            this.charArray = charArray;
            for(i = 0; i < charArray.length; i++)
            {
                temp = search(rootNode, "", charArray[i]);
                finalBitPattern += temp+" ";
                ban=false;
                for (j=0;j < i; j++){
                    if (i!=j){
                        t1=charArray[j];
                        t2=charArray[i];
                        if (t1!=t2){
                            ban=false;
                        }
                        else if (t1==t2){
                            ban=true;
                            break;
                        }
                    }
                }
                if (ban==false){
                    codigos[con]=String.valueOf(temp);
                    tabla[con]=charArray[i];
                    con++;
                }
              
            }
            chars=charArray;
      //  System.out.println("My final Bit Pattern: "+finalBitPattern);
    }
    
    public String[] getCodigos(){
        return codigos;
    }
    
    public char[] getChar(){
        return tabla;
    }
    
    public int[] Frecuencia(){
        for (j=0;j < codigos.length; j++){
            cuantos=0;
            for(i = 0; i < charArray.length; i++){
                if (tabla[j]==chars[i]){
                    cuantos++;
                }
            }
            frec[j]=cuantos;
        }    
        return frec;
    }
    
    public String search(Node rootNode, String value,char myChar)
    {
        String valueL ="";
        if(rootNode != null)
        {
            if(rootNode.left != null)
                valueL = search(rootNode.left, value+"0", myChar);
            if(rootNode.c == myChar)
                return value;

            else
            {
                if(valueL == "")
                {
                    return search(rootNode.right, value+"1",myChar);
                }
                else
                {
                    return valueL;
                }
            }
        }
        else
        {
            return "";
        }
    }
        
}
